#!/usr/bin/env python
# -*- coding: utf-8 -*-

from google.appengine.ext import webapp
from google.appengine.api import urlfetch
from google.appengine.ext.webapp import template

from BeautifulSoup import BeautifulSoup
import urllib

def getSearchResult(query):
    search_result = '';
    query = urllib.quote( query )
    
    result = urlfetch.fetch("http://www.google.co.kr/search?q=" + query)
    if result.status_code == 200:
        soup  = BeautifulSoup( unicode(result.content, 'cp949' ).encode('utf-8') )
        items = soup('li')
        for item in items:
            links = item.findAll(name='a', attrs={'class': 'l'})
            
            for link in links:
                href_attr = link['href']  
                href_attr = href_attr[ href_attr.find('http://'): ]
                link['href'] = '/GetMp3Links?url=' + href_attr
            search_result += item.__str__()
            
    return search_result;

class SearchTistoryMp3Page(webapp.RequestHandler):    
    def get(self):
        self.response.headers['Content-Type'] = 'text/html;charset=UTF-8'
        
        search_result = ''
        query = self.request.get('query').encode('utf-8')
        if query != '':
            query += ' mp3 site:tistory.com'
            query = query.replace(' ', '+')
            search_result = getSearchResult(query)

        template_values = {
                           'search_results': search_result,
                          }
        
        import os
        path = os.path.join(os.path.dirname(__file__), 'html/SearchTistoryMp3Page.html')
        self.response.out.write(template.render(path, template_values))
        
# EOF